Ext.ns('AIR2.Project');
/***************
 * Project creation modal window
 * 
 * Opens a modal window to allow creating new projects
 *
 * @cfg {HTMLElement} originEl (optional) origin element to animate from
 * @cfg {Boolean} redirect (default false) redirect on success
 * @cfg {Function} callback (optional) function passed boolean success
 */
AIR2.Project.Create = function(cfg) {
    // system users choose from all organizations; normal users from their own
    var orgUrl;
    if (AIR2.USERINFO.type == 'S') {
        orgUrl = AIR2.HOMEURL+'/organization';
    }
    else {
        orgUrl = AIR2.HOMEURL+'/user/'+AIR2.USERINFO.uuid+'/organizations';
    }

    var flds = [{
        fieldLabel: 'Display Name',
        name: 'prj_display_name'
    },{
        xtype: 'air2remotetext',
        fieldLabel: 'Short Name',
        name: 'prj_name',
        remoteUrl: AIR2.HOMEURL + '/project/name.json',
        maxLength: 32,
        maskRe: /[a-z0-9_\-]/
    },{
        xtype: 'textarea',
        fieldLabel: 'Summary',
        name: 'prj_desc',
        height: 100
    },{
        xtype: 'air2combo',
        fieldLabel: 'Shared',
        name: 'prj_shared_flag',
        width: 80,
        choices: [[true, 'Yes'], [false, 'No']],
        value: true
    }];

    if (!cfg.org_uuid) {
        flds.push({
            xtype: 'air2searchbox',
            id:'air2-organization-picker',
            name: 'org_uuid',
            fieldLabel: 'Organization',
            searchUrl: orgUrl,
            valueField: 'org_uuid',
            displayField: 'org_display_name',
            formatComboListItem: function(v) {
                return v.org_display_name;
            }
        });
    }
    else {
        flds.push({
            xtype:'hidden',
            name:'org_uuid',
            value:cfg.org_uuid
        });
    }

    var w = new AIR2.UI.Window({
        title: 'Create Project',
        closeAction: 'close',
        width: 400, 
        height: 265,
        formAutoHeight: true,
        items: {
            xtype: 'form',
            unstyled: true,
            style: 'padding: 10px 10px 0',
            labelWidth: 85,
            defaults: {
                xtype: 'textfield',
                allowBlank: false,
                width: 290,
                msgTarget: 'under'
            },
            items: flds,
            bbar: [{
                xtype: 'air2button',
                air2type: 'SAVE',
                air2size: 'MEDIUM',
                text: 'Save',
                handler: function() {
                    var f = w.get(0).getForm(), el = w.get(0).el;

                    // validate and fire the ajax save
                    if (f.isValid()) {
                        el.mask('Saving...');
                        Ext.Ajax.request({
                            url: AIR2.HOMEURL + '/project.json',
                            params: {radix: Ext.encode(f.getFieldValues())},
                            callback: function(opt, success, rsp) {
                                if (success) {
                                    el.unmask();
                                    el.mask('Loading new Project...');
                                    var d = Ext.decode(rsp.responseText);
                                    if (d.success && d.radix.prj_uuid) {
                                        if (cfg.callback) cfg.callback(true);
                                        if (cfg.redirect) {
                                            location.href = AIR2.HOMEURL + '/project/' + d.radix.prj_uuid;
                                        }
                                        else {
                                            w.close();
                                        }
                                        return;
                                    }
                                }
                                // failed
                                //Logger(rsp);
                                if (cfg.callback) cfg.callback(true, rsp.responseText);
                                el.unmask();
                                if (rsp.status == 403) {
                                    alert("Permission denied. Do you have write permission to the selected Organization?");
                                    return;
                                }
                                alert("TODO: FAILED\n"+rsp.responseText);
                            }
                        });
                    }
                }
            },'  ',{
                xtype: 'air2button',
                air2type: 'CANCEL',
                air2size: 'MEDIUM',
                text: 'Cancel',
                handler: function() {w.close();}
            }]
        }
    });

    // add listener to filter out orgs the user cannot WRITE to
    if (!cfg.org_uuid && AIR2.USERINFO.type != 'S') {
        var cb = Ext.getCmp('air2-organization-picker');
        cb.store.on('load', function(thisStore,recs,opts) {
            thisStore.each(function(rec) {
                var uuid = rec.get('org_uuid');
                if (!(AIR2.AUTHZ.WRITER & AIR2.USERAUTHZ[uuid])) {
                    //Logger("filter out non-WRITER for " + uuid);
                    thisStore.remove(rec);
                }
                return true;
            });
        });
    }
    if (cfg.originEl) w.show(cfg.originEl);
    else w.show();
    return w;
}
